import { ProForm, ProFormInstance, ProFormText } from "@ant-design/pro-components";
import styles from "./index.module.less";
import { useRef, useState } from "react";
import { Affix, Button, Col, Flex, Row, Space, message } from "antd";
import { PHONE_REG, REG_EXP_BY_URL } from "@/utils/pattern";
import Upload from "@/components/Upload";
import { CheckCircleOutlined } from "@ant-design/icons";
import { MAIN_PRIMARY_COLOR } from "@/enums";
import { useRequest } from "ahooks";
import { addShopsApi } from "@/api/modules/merchant";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import { useLocation, useNavigate } from "react-router-dom";
import dayjs from "dayjs";

export default () => {
	const formRef = useRef<ProFormInstance | undefined>();
	const { state } = useLocation();
	const isViewRef = useRef(state?.isView);
	const isEditRef = useRef(state?.isEdit);
	const [isEditFlag, setIsEditFlag] = useState(!isViewRef.current);
	const navigate = useNavigate();

	const shop_id = state?.data?.shop_id;
	const updated_at = state?.data?.updated_at;

	const { loading, runAsync } = useRequest(addShopsApi, { manual: true });

	const handleRequest = async () => {
		if (shop_id) {
			return state?.data;
		}

		return {};
	};

	const handleSubmit = (type: string) => {
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			const values = formRef.current?.getFieldFormatValue?.();
			runAsync({
				...values,
				shop_id
			}).then(res => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success("保存成功！");
					// if (type === "create") {
					// 	formRef.current?.resetFields?.();
					// } else if (type === "update") {
					// 	setIsEditFlag(e => !e);
					// }
					navigate("/merchants");
				}
			});
		});
	};

	const handleBack = (type: string) => {
		// switch (type) {
		// 	case "update":
		// 		formRef.current?.setFieldsValue(state?.data);
		// 		setIsEditFlag(e => !e);
		// 		break;
		// 	case "create":
		// 		formRef.current?.resetFields?.();
		// }
		navigate("/merchants");
	};

	return (
		<div className={styles.container}>
			<div className={styles.title}>店铺基础信息</div>
			<ProForm
				disabled={!isEditFlag}
				request={handleRequest}
				className={styles.form}
				submitter={false}
				formRef={formRef}
				layout="horizontal"
				labelCol={{ span: 6 }}
			>
				<Row>
					<Col span={24}>
						<ProFormText
							labelCol={{ span: 3 }}
							label="店铺名称"
							name="shop_name"
							placeholder="最多允许输入20个汉字"
							fieldProps={{
								maxLength: 20,
								showCount: isEditFlag
							}}
							rules={[
								{ required: isEditFlag, message: "请输入店铺名称" },
								{ max: 20, message: "最多允许输入20个汉字" }
							]}
						/>
					</Col>
					{/* <Col span={12}>
						<ProFormText
							label="店铺ID"
							name="shop_id"
							required
							placeholder=""
							fieldProps={{
								disabled: true
							}}
						/>
					</Col> */}
				</Row>
				<Row>
					<Col span={12}>
						<ProFormText
							label="联系人"
							name="contacter"
							rules={[{ required: isEditFlag, message: "请输入联系人姓名" }]}
							placeholder="请输入联系人姓名"
						/>
					</Col>
					<Col span={12}>
						<ProFormText
							rules={[
								{
									required: isEditFlag,
									message: "请输入联系人电话"
								},
								{
									pattern: PHONE_REG,
									message: "请输入正确的手机号"
								}
							]}
							label="联系电话"
							name="contact_phone"
							placeholder="请输入联系人电话"
						/>
					</Col>
				</Row>
				<ProFormText
					labelCol={{ span: 3 }}
					label="联系地址"
					rules={[{ required: isEditFlag, message: "请输入联系人地址" }]}
					placeholder={"请输入联系人地址"}
					name="contact_address"
				/>
				<Row>
					<Col span={12}>
						<ProFormText label="公司名称" name="company_name" placeholder="请输入公司名称" />
					</Col>
					<Col span={12}>
						<ProFormText label="经营许可证" name="business_license" placeholder="请输入公司经营许可证" />
					</Col>
				</Row>
				<Row>
					<Col span={12} className={styles.upload_wrap}>
						<ProForm.Item
							label="店铺头像"
							name="shop_avatar"
							rules={[{ required: isEditFlag, message: "请上传店铺头像" }]}
							transform={(v, name) => ({
								[name]: v?.[0]?.url
							})}
						>
							<Upload maxSize={3} canRemove={isEditFlag} />
						</ProForm.Item>
						<Row>
							<Col span={24} offset={6}>
								<div className={styles.upload_tips}>
									<span>图片要求：比例为1:1，大小3m内；</span>
								</div>
							</Col>
						</Row>
					</Col>
					<Col span={12}>
						<ProFormText
							name="promotional_material"
							label="宣传素材"
							rules={[
								{ required: isEditFlag, message: "请输入宣传素材" },
								{ pattern: REG_EXP_BY_URL, message: "请输入正确的网址" }
							]}
							placeholder={"请输入视频或图片链接，比例为16:9"}
						/>
					</Col>
				</Row>
			</ProForm>
			<Affix offsetBottom={0}>
				<Flex justify="center" className={styles.btns}>
					<Space size={10}>
						{isViewRef.current || isEditRef.current ? (
							<>
								{isEditFlag ? (
									<>
										<Button ghost type="primary" onClick={() => handleBack("update")}>
											取消
										</Button>
										<Button loading={loading} type="primary" onClick={() => handleSubmit("update")}>
											保存
										</Button>
										{Boolean(updated_at) && (
											<Space size={10}>
												<CheckCircleOutlined style={{ color: MAIN_PRIMARY_COLOR }} />
												<span style={{ color: "#000" }}>最后保存于{dayjs(updated_at).format("YYYY-MM-DD")}</span>
											</Space>
										)}
									</>
								) : (
									<Button type="primary" onClick={() => setIsEditFlag(e => !e)}>
										编辑
									</Button>
								)}
							</>
						) : (
							<>
								<Button ghost type="primary" onClick={() => handleBack("create")}>
									取消创建
								</Button>

								<Button type="primary" onClick={() => handleSubmit("create")} loading={loading}>
									创建店铺
								</Button>
							</>
						)}
					</Space>
				</Flex>
			</Affix>
		</div>
	);
};
